<!--
 * @页面名称:全局模板
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="card globalTemplate">
    <!-- 顶部操作按钮 -->
    <div style="margin-bottom: 10px">
      <el-button type="primary" @click="add">新增</el-button>
    </div>
    <!-- table表格 -->
    <div style="height: calc(100% - 42px)">
      <Stable :columns="tableSetting.columns" :data="tableSetting.data"></Stable>
    </div>
    <!-- 新增修改弹出框 -->
    <modal v-model:visible="dialogSetting.visible" width="700" :title="dialogSetting.title" @ok="handle">
      <el-form label-width="90px" :model="formData" :rules="rules" ref="formRef">
        <el-form-item label="模板名称:" prop="CRM_FileName">
          <el-input v-model="formData.CRM_FileName" placeholder="请输入模板名称..."></el-input>
        </el-form-item>
        <el-form-item label="文件大小:" prop="CRM_FileSize">
          <label>{{ fileSizeUnit({ cellValue: formData.CRM_FileSize }) }}</label>
        </el-form-item>
        <el-form-item label="顺序号:" prop="CRM_Order">
          <el-input type="number" v-model="formData.CRM_Order" placeholder="请输入顺序号..."></el-input>
        </el-form-item>
        <el-form-item label="是否启用:" prop="CRM_Enabled">
          <el-checkbox v-model="formData.CRM_Enabled"></el-checkbox>
        </el-form-item>
        <el-form-item label="模板文件:" prop="CRM_Entity">
          <el-upload
            style="width: 100%"
            accept=".xls,.xlsx"
            v-model:file-list="fileList"
            :auto-upload="false"
            :on-change="handlerFileChange"
            :on-remove="fnFileRemove"
          >
            <el-button :icon="Upload"> 上传模板 </el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注:" prop="CRM_Remark">
          <el-input :rows="2" type="textarea" v-model="formData.CRM_Remark"></el-input>
        </el-form-item>
      </el-form>
      <el-divider content-position="left">内容配置</el-divider>
      <el-form label-width="90px" :model="formData2" :rules="rules2" ref="formRef2">
        <el-row>
          <el-col :span="12">
            <el-form-item label="行数:" prop="Columns">
              <el-input v-model="formData2.Columns" placeholder="请输入行数..."></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="列数:" prop="Rows">
              <el-input v-model="formData2.Rows" placeholder="请输入列数..."></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="空行补齐:" prop="IsBlankLine">
              <el-checkbox v-model="formData2.IsBlankLine"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分页:" prop="IsPaging">
              <el-checkbox v-model="formData2.IsPaging"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="遍历顺序:" prop="CRM_Order">
              <el-select v-model="formData2.Orientation" placeholder="请选择遍历顺序...">
                <el-option value="Horizontal">Horizontal</el-option>
                <el-option value="Vertical">Vertical</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据源:" prop="DataSource">
              <el-select v-model="formData2.DataSource" placeholder="请选择数据源...">
                <el-option value="案卷数据">案卷数据</el-option>
                <el-option value="文件数据">文件数据</el-option>
                <el-option value="附件数据">附件数据</el-option>
                <el-option value="全文数据">全文数据</el-option>
                <el-option value="分类数据">分类数据</el-option>
                <el-option value="其他">其他</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="OrderBy:">
              <el-input v-model="formData2.OrderBy" placeholder="输入排序信息..." />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <a-form-item label="SQL" :label-col="{ span: 3 }">
              <a-input v-model="formData2.SQL" type="textarea" placeholder="输入SQL查询语句..." />
            </a-form-item>
          </el-col>
        </el-row>
      </el-form>
    </modal>
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive, onMounted, nextTick } from "vue";
import type { FormInstance, FormRules, UploadUserFile } from "element-plus";
import { Upload } from "@element-plus/icons-vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { fileSizeFormat } from "@/utils/formatter";
import { arrayToBase64, base64ToBlob, base64ToBuffer, fileToBase64, isBase64 } from "@/utils/util";
import { saveAs } from "file-saver";

const { proxy } = useCurrentInstance();
// 表格配置
const tableSetting = reactive({
  columns: [
    { field: "CRM_FileName", title: "模板名称", sortable: true },
    { field: "CRM_FileSize", title: "文件大小", sortable: true, formatter: fileSizeFormat },
    {
      field: "CRM_Enabled",
      title: "启用",
      sortable: true,
      slots: {
        default: ({ row }: { row: any }) => {
          return [<el-checkbox disabled v-model={row.CRM_Enabled}></el-checkbox>];
        }
      }
    },
    { field: "CRM_Remark", title: "描述", sortable: true },
    {
      title: "操作",
      sortable: true,
      width: 140,
      slots: {
        default: ({ row }: any) => {
          return [
            <el-space>
              <el-link underline={false} type="primary" onClick={() => edit(row)}>
                修改
              </el-link>
              <el-link underline={false} type="primary" onClick={() => del(row)}>
                删除
              </el-link>
              <el-link underline={false} type="primary" onClick={() => download(row)}>
                下载
              </el-link>
            </el-space>
          ];
        }
      }
    }
  ],
  data: [] as any
});
// 弹出框配置
const dialogSetting = reactive({
  visible: false,
  title: "",
  type: "add"
});
// 表单配置
const formData = ref({
  CRM_FileName: "",
  CRM_Enabled: true,
  CRM_Remark: "",
  CRM_Order: "",
  CRM_FileSize: "",
  CRM_Config: "",
  CRM_Entity: ""
});
// 表单配置2
const formData2 = ref({
  Columns: 1,
  Rows: 1,
  IsBlankLine: true,
  IsPaging: true,
  DataSource: "",
  OrderBy: "",
  Orientation: "Vertical",
  SQL: ""
});
// 单击保存数据
const clickObj = ref();
// 表单实例
const formRef = ref<FormInstance>();
// 表单实例2
const formRef2 = ref<FormInstance>();
// 表单规则
const rules = reactive<FormRules>({
  CRM_FileName: [{ required: true, message: "请输入模板名称!", trigger: "blur" }]
});
// 表单规则2
const rules2 = reactive<FormRules>({
  Columns: [{ required: true, message: "请输入行数!", trigger: "blur" }],
  Rows: [{ required: true, message: "请输入列数!", trigger: "blur" }],
  DataSource: [{ required: true, message: "请选择数据源!", trigger: "blur" }]
});
// 模板上传控件的已上传文件列表
const fileList = ref<UploadUserFile[]>([]);
// 表格数据
const getData = () => {
  proxy.$vueAxios.get("Master_Base_Design_CommonReportModule/Get", { order: "CRM_Order asc" }).then((res: any) => {
    tableSetting.data = res.List;
  });
};
// 新增事件
const add = () => {
  fnClearFormModel();
  dialogSetting.visible = true;
  dialogSetting.title = "新增";
};
// 修改
const edit = (row: any) => {
  fnClearFormModel();
  clickObj.value = row;
  dialogSetting.visible = true;
  dialogSetting.title = "修改";
  nextTick(() => {
    formData.value.CRM_Order = row.CRM_Order;
    formData.value.CRM_FileName = row.CRM_FileName;
    formData.value.CRM_FileSize = row.CRM_FileSize;
    formData.value.CRM_Enabled = row.CRM_Enabled;
    formData.value.CRM_Config = row.CRM_Config;
    formData.value.CRM_Remark = row.CRM_Remark;
    formData2.value = JSON.parse(formData.value.CRM_Config);
  });
};
// 删除
const del = (row: any) => {
  proxy.$messageBox
    .confirm("确定删除该数据？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(() => {
      proxy.$vueAxios.post("Master_Base_Design_CommonReportModule/Delete", [row.CRM_ID]).then((res: any) => {
        if (res.Mark) {
          getData();
          proxy.$message.success("删除成功");
        } else {
          proxy.$message.error("删除失败");
        }
      });
    });
};
// 弹框确认事件
const handle = () => {
  // 将配置信息转换成json格式字符
  formData.value.CRM_Config = JSON.stringify(formData2.value);
  new Promise<void>((resolve, reject) => {
    let formValid: any = null;
    let formValid2: any = null;
    // 校验整体内容部分
    formRef.value?.validate().then(valid => {
      formValid = valid;
      if (formValid && formValid2) {
        resolve();
      } else if (formValid2 != null) {
        reject(new Error());
      }
    });
    formRef2.value?.validate().then(valid => {
      formValid2 = valid;
      if (formValid && formValid2) {
        resolve();
      } else if (formValid2 != null) {
        reject(new Error());
      }
    });
  }).then(() => {
    switch (dialogSetting.title) {
      case "新增":
        proxy.$vueAxios
          .post("Master_Base_Design_CommonReportModule", {
            crM_ID: proxy.$global.createID(),
            crM_Order: formData.value.CRM_Order,
            crM_Enabled: formData.value.CRM_Enabled,
            crM_FileName: formData.value.CRM_FileName,
            crM_FileSize: formData.value.CRM_FileSize,
            crM_Entity: formData.value.CRM_Entity,
            crM_Config: formData.value.CRM_Config,
            crM_Remark: formData.value.CRM_Remark
          })
          .then(() => {
            proxy.$message.success("添加成功");
            dialogSetting.visible = false;
            fnClearFormModel();
            getData();
          });
        break;
      case "修改":
        proxy.$vueAxios
          .put("Master_Base_Design_CommonReportModule", {
            crM_ID: clickObj.value.CRM_ID,
            crM_Order: formData.value.CRM_Order,
            crM_Enabled: formData.value.CRM_Enabled,
            crM_FileName: formData.value.CRM_FileName,
            crM_FileSize: formData.value.CRM_FileSize,
            crM_Entity: formData.value.CRM_Entity,
            crM_Config: formData.value.CRM_Config,
            crM_Remark: formData.value.CRM_Remark
          })
          .then(() => {
            proxy.$message.success("修改成功");
            dialogSetting.visible = false;
            fnClearFormModel();
            getData();
          });
        break;
    }
  });
};
// 文件单位转换（字节转KB、MB）
const fileSizeUnit = ({ cellValue }: any) => {
  if (!cellValue) {
    return "";
  }
  const kb = cellValue / 1024.0;
  if (kb > 1024) {
    const mb = kb / 1024;
    return mb.toFixed(2) + "MB";
  }
  return kb.toFixed(2) + "KB";
};
// 上传文件
const handlerFileChange = (file: any) => {
  formData.value.CRM_FileName = file.name;
  formData.value.CRM_FileSize = file.size;
  // 去掉base64文件类型头，避免后端模型绑定时数据类型验证失败
  fileToBase64(file.raw, (res: any) => {
    base64ToBlob(res, (res2: string) => {
      formData.value.CRM_Entity = res2;
    });
  });
  return false;
};
// 从上传控件中移除上传项时
const fnFileRemove = () => {
  formData.value.CRM_FileSize = "";
  formData.value.CRM_Entity = "";
};
// 清空弹窗表单的内容
const fnClearFormModel = () => {
  formData.value = {
    CRM_FileName: "",
    CRM_Order: "",
    CRM_Enabled: true,
    CRM_Config: "",
    CRM_Remark: "",
    CRM_FileSize: "",
    CRM_Entity: ""
  };
  // 重置配置项表单内容
  formData2.value = {
    Columns: 1,
    Rows: 1,
    IsBlankLine: true,
    IsPaging: true,
    DataSource: "",
    OrderBy: "",
    Orientation: "Vertical",
    SQL: ""
  };
  // 清空文件选择列表
  fileList.value = [];
};
// 下载
const download = (row: any) => {
  fnDownload(row.CRM_Entity, row.CRM_FileName);
};
// 二进制文件下载方法
const fnDownload = (content: any, fileName: any) => {
  // 将xls内容转换为Blob对象
  if (isBase64(content)) {
    // 是base64直接下载
    const data = base64ToBuffer(content);
    saveAs(data, fileName);
  } else {
    // 不是base64先转换下载
    const base64 = arrayToBase64(content);
    const data = base64ToBuffer(base64);
    saveAs(data, fileName);
  }
};
onMounted(() => {
  getData();
});
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
